const dayjs = require('dayjs');
import Day from 'dayjs';
import BaseModel from './base_model';

/**
 * 文档领域模型
 * 封装文档业务逻辑与规则
 */
class DocumentModel extends BaseModel {
  constructor(data = {}) {
    super(data);
    // 基本属性
    this._id = data._id || '';
    this.projectId = data.projectId || '';
    this.title = data.title || '';
    this.fileId = data.fileId || '';
    this.fileUrl = data.fileUrl || '';
    this.fileType = data.fileType || '';
    this.fileSize = data.fileSize || 0;
    this.uploaderId = data.uploaderId || '';
    this.uploaderName = data.uploaderName || '';
    this.uploadTime = data.uploadTime || 0;
    this.version = data.version || '1.0';
    this.description = data.description || '';
    this.tags = data.tags || [];
    
    // 计算属性
    this.formattedUploadTime = this.uploadTime ? Day(this.uploadTime).format('YYYY-MM-DD HH:mm') : '';
    this.formattedFileSize = this.getFormattedSize();
    this.fileIcon = this.getFileIcon();
  }
  
  /**
   * 获取文件图标
   */
  getFileIcon() {
    const typeMap = {
      'pdf': 'pdf-icon',
      'doc': 'word-icon',
      'docx': 'word-icon',
      'xls': 'excel-icon',
      'xlsx': 'excel-icon',
      'ppt': 'ppt-icon',
      'pptx': 'ppt-icon',
      'jpg': 'image-icon',
      'jpeg': 'image-icon',
      'png': 'image-icon',
      'txt': 'text-icon'
    };
    
    const ext = (this.fileType || '').toLowerCase();
    return typeMap[ext] || 'file-icon';
  }
  
  /**
   * 格式化文件大小
   */
  getFormattedSize() {
    if (this.fileSize < 1024) {
      return `${this.fileSize}B`;
    } else if (this.fileSize < 1024 * 1024) {
      return `${(this.fileSize / 1024).toFixed(2)}KB`;
    } else {
      return `${(this.fileSize / (1024 * 1024)).toFixed(2)}MB`;
    }
  }
  
  /**
   * 转换为存储格式
   */
  toStorage() {
    const data = {...this};
    
    // 处理上传时间
    if (!data.uploadTime) {
      data.uploadTime = dayjs().valueOf();
    }
    
    return data;
  }
  
  /**
   * 验证文档数据是否有效
   */
  validate() {
    const errors = {};
    
    if (!this.title) errors.title = '文档标题不能为空';
    if (!this.projectId) errors.projectId = '项目ID不能为空';
    if (!this.fileId) errors.fileId = '文件ID不能为空';
    
    return {
      valid: Object.keys(errors).length === 0,
      errors
    };
  }
}

export default DocumentModel; 